﻿@{
    ViewBag.Title = "Common Command";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
        <ol class="breadcrumb">
            <li><a href="/Home/Home">Home</a></li>
              <li class="active">App StartUp</li>
        </ol>
     
           
            <div id="introduction">
                <h1 class="text-left">Initialization</h1>
                <h3>Application StartUp</h3>
            </div>
            <p>
                Initialization
                <pre>Init()<code>
public void Init(HttpApplication context)
{
     context.BeginRequest += BeginRequest;
}
                </code></pre>The Context is added to the current ongoing request.<br />
                HttpApplication is the base class used by user in the Main Class.
            </p>
            <p>
                An Event is defined, BeginRequest which calls explicit EnsureDependeciesRegistered module.
                <pre><code>
        private static void BeginRequest(object sender, EventArgs e)
        {
            EnsureDependenciesRegistered();
            if (_initialized) return;
            lock (Lock)
            {
                if (_initialized) return;
                BootStrapper();
                StartUpMvcApp();
                _initialized = true;
            }
        }
</code></pre>
                An Request is initialized when everything is ready and started, after all the modules are loaded the "_initialized flag is set True". An Lock also needs to be setup so that when performing Initiallization none of the resourse should be in use that could conflict in this phase.
            </p>
            <pre>EnsureDependencies<code>private static void EnsureDependenciesRegistered()
        {
            if (_dependenciesRegistered) return;
            lock (Lock)
            {
                if (_dependenciesRegistered) return;
                ObjectFactory.ResetDefaults();
                _dependenciesRegistered = true;
            }
        }</code>All Dependencies are Reset to Default.</pre>
            <p>Now How to Initialize Bootstrape</p>
            <pre><code>public static void BootStrapper()
        {
            if (_initialized) return;
            CheckConfigurations();
            ConfigureIocTool();
            ConfigureDomainEvents();
            ConfigureAutoMapper();
            ConfigureSignalR();
            ConfigureNServiceBus();
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
        }</code></pre>
            <h3>Starting Up MVC Application</h3>
            <pre>Start Up Code Module<code>
private static void StartUpMvcApp()
 {
   SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
   VersionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(HomeController)).Location);
   ControllerBuilder.Current.SetControllerFactory(new ControllerFactory());
   GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new SmartHttpControllerActivator());
   AreaRegistration.RegisterAllAreas();
   GlobalConfiguration.Configure(RegisterWebApi);
   RegisterGlobalFilters(GlobalFilters.Filters);
   RegisterRoutes(RouteTable.Routes);
   RegisterBundles(BundleTable.Bundles);
   RegisterFormatters();
 }
</code></pre>
            <p>
                <b>Description: </b> First, SpreadsheetInfo is used to provide static licensing methods and diagnostics. Hence its licence is set to "Free-Limited-Key"<br />
                Second, The FileVersionInfo Class is used to get the version information of the Assembly being loaded for "HomeController"<br />
            </p>
            <article>
                Then ControllBuiler is Used to create dynamic Controllers which is hence creating an Controller through <b>ControllerFactory</b>,
                a controllerFactory get the instance of the requested Controller and the controller type, which then builds the controller.
                The global configuration is used of the Http class to replace the controller being intiated by SmartHttpControllerActivator which is a type of IHttpController.
                The controller is then being registered to every area available. <br />
                Then an RegisterWebApi is called which routes the controller to their deiffrent routes as defined.
                <pre><code>
    private static void RegisterWebApi(HttpConfiguration configuration)
        {
            configuration.MapHttpAttributeRoutes();
            configuration.Routes.MapHttpRoute("DefaultApiWithId", "api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
            configuration.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}");
            configuration.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get.Method) });
            configuration.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post.Method) });
            configuration.Routes.MapHttpRoute("DefaultApiPut", "api/{controller}", new { action = "Put" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Put.Method) });
            configuration.Routes.MapHttpRoute("DefaultApiDelete", "api/{controller}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Delete.Method) });
        }
</code></pre>
                Again an global filter filter the controller by rules.<br />
                <pre><code>
 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
</code></pre>
                An Module Called RegisterRoute is used not to route to protected location of the system.
                Last But not least Bundles are called to load all Scripts and Style for the controller, which it will need to display.<br />
                <pre><code>
    public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/prejavascript").Include(
                "~/Public/vendor/jquery/jquery.min.js",
                "~/Public/vendor/jquery/jquery.signalR.min.js",
                "~/Public/vendor/highcharts/highcharts.js",
                "~/Public/vendor/highcharts/exporting.js",
                "~/Public/vendor/md5/md5.js",
                "~/Public/vendor/underscore/underscore.min.js",
                "~/Public/vendor/raphael/raphael.min.js",
                "~/Public/vendor/justgage/justgage.min.js",
                "~/Public/api/jquery.extensions.js",
                "~/Public/api/initialization.js"));
        }
</code></pre>
                Module called RegisterFormatters is an JsonSerialization Object which is used to format the data for the controller.
                <pre><code>
private static void RegisterFormatters()
{
   var jsonSettings = new JsonSerializerSettings
   {
   ContractResolver = new CamelCasePropertyNamesContractResolver(),
   DateFormatHandling = DateFormatHandling.IsoDateFormat,
   };
      GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(jsonSettings));  
}
</code></pre><h3>Dependency Injection</h3>
                <pre>Dependency Injection<code>private static void ConfigureIocTool()
        {
            ObjectFactory.Initialize(x => x.Scan(scan =>
            {
                scan.TheCallingAssembly();
                scan.AssemblyContainingType&lt;sanelibregistry>();
                scan.AssemblyContainingType&lt;commonregistry>();
                scan.AssemblyContainingType&lt;coreregistry>();
                scan.AssemblyContainingType&lt;uiregistry>();
                scan.WithDefaultConventions();
                scan.LookForRegistries();
            }));
        }</code>This Scans assemblies to auto registery policies.</pre>

            </article>
            <div>
                <h3>Some Other Initialization</h3>
                <ol>
                    <li>
                        Configure Domain Events : <br /> <code>EventCoordinator.Container = ObjectFactory.GetInstance&lt;icontainer>();</code>
                    </li>
                    <li>
                        Configure AutoMapper : <br /><code>AutoMapperConfiguration.Configure(ObjectFactory.GetInstance);</code>
                    </li>
                    <li>
                        Configure SignalR : <br /><code>GlobalHost.DependencyResolver = ObjectFactory.GetInstance&lt;microsoft.aspnet.signalr.idependencyresolver>();</code>
                    </li>
                    <li>
                        ApplyAppConfig(string key, string value) : <br /> The application configures through a class object WebConfigurationManager.<br />
                        <code>config.AppSettings.Settings.AllKeys.Any(x => x == key);</code>
                    </li>
                    <li>
                        Check Configuration : <br /> Every Configuration is checked like Network, System, Enviroment Configuration and Application. <br />
                        <code>var webPath = HostingEnvironment.MapPath("~");</code>
                        <code>
                            var srcWebPath = webPath + "..\\Deployment\\Configs";<br />
                            if (!Directory.Exists(srcWebPath)) return true;
                        </code>
                    </li>
                    <li>
                        Test Configuration : <code>
                            ApplyAppConfig("StartupTime", DateTime.Now.ToString(CultureInfo.InvariantCulture));<br />
                            var generalConfig = ConfigProvider.GetGeneralConfig();
                        </code>
                        <pre><code>generalConfig = new GeneralConfig
            {
                RunMode = "Debug",
                DoNotLogInfo = false,
                LogOutputTo = "File",
                StoreConfigInDatabase = false,
                ApplicationBaseUrl = "http://localhost:9095",
                ApplicationHealthUrl = "http://localhost:9095/MemberRegistration/record"
            };
            ConfigProvider.SetGeneralConfig(generalConfig, true);</code></pre>
                    </li>
                </ol>
            </div>
       
